package ua.kiev.tosik.price.modules.clients.database;

import org.apache.log4j.Logger;
import ua.kiev.tosik.price.conf.AppConfig;
import ua.kiev.tosik.price.database.dao.IClientsDao;
import ua.kiev.tosik.price.database.factory.AbstractDbFactory;
import ua.kiev.tosik.price.models.Clients;

import javax.swing.*;

public class DataUpdateWorker extends SwingWorker<Clients, Void> {

	private static Logger logger = Logger.getLogger("ua.kiev.tosik.price.modules.clients.database");
	private Clients client;
	private IClientsDao clientsDao;

	public DataUpdateWorker() {
		super();
		logger.debug("Initialize DataLoadWorker");
		try {
			clientsDao = AbstractDbFactory.getInstance(AppConfig.getInstance().get("app.dbtype")).createClientsDao();
		} catch (Exception e) {
			logger.error(e);
		}
	}

	@Override
	protected Clients doInBackground() throws Exception {
		if ( client != null ) {
			firePropertyChange("SAVE_START", false, AppConfig.getInstance().get("clients.editor.data.save"));
			client = clientsDao.update(client);
		}
		firePropertyChange("SAVE_DONE", false, true);
		return client;
	}

	@Override
	protected void done() {
		try {
			client = get();
			// firePropertyChange("ClientsList", null, client);
			if ( client != null ) {
				// MainPanel.getInstance().getTable().getModel().addRow(0, client);
				firePropertyChange("UPDATE_OK", null, client);
			} else {
				logger.error("Can't create record");
			}
			// MainPanel.getInstance().getToolBar().setRecordFoundInfoText("Found " + clientsList.size() + " record(s)");
		} catch (Exception e) {
			firePropertyChange("SAVE_ERROR", null, e);
			logger.error(e);
		}
	}

	public void setClient(Clients client) {
		this.client = client;
	}
}
